iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0
自我挑戰組

Powershell 入门系列 第 16

Powershell 入门参数属性(2)

  • 分享至 

  • xImage
  •  

前面我们讲了怎么通过参数的属性限制参数的个数和长度。今天我们来看看,通过参数的属性,限制参数的格式以及参数的可选集(特定的值)。

首先我们来看看今天的示例脚本:

function test-net_port {
    [cmdletbinding()]
    param(
        [parameter(mandatory=$true,Helpmessage="Enter the name of a computer to check connectivity to.")]
        [ValidateCount(1,5)]
        [ValidateLength(1,15)]
        [ValidatePattern("SZ[A-Z]{2,3}\d{1,2}$")]  #computerName 必须要满足正则表达式
        [string[]]$computerName,
        [parameter(mandatory=$false)]
        [ValidateSet(80,443,22)]    # port 的值,只能是 80,443 和 22 其中的一个
        [int] $port
    )
    foreach ($computer in $computerName) {
        Write-Verbose "Now testing $computer."
        if ($port -eq "")
        {
            $ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue
        } else {
            $ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue -Port $port
        }
        if ($ping){
            Write-Output $ping
        } else {
            Write-Verbose "Ping failed on $computer. Check the network connection."
            Write-Output $ping
        }
    }
}

运作结果:

PS C:\Users> test-net_port -computerName SZSVR1
False

PS C:\Users> test-net_port -computerName SZSVR001
test-net_port : Cannot validate argument on parameter 'computerName'. The argument "SZSVR001" does not match the "SZ[A-Z]{2,3}\d{1,2}$" pattern. Supply an argument that matches 
"SZ[A-Z]{2,3}\d{1,2}$" and try the command again.
At line:1 char:29
+ test-net_port -computerName SZSVR001
+                             ~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [test-net_port], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port

PS C:\Users> test-net_port -computerName SZSVR01 -port 23
test-net_port : Cannot validate argument on parameter 'port'. The argument "23" does not belong to the set "80,443,22" specified by the ValidateSet attribute. Supply an argument that is in 
the set and then try the command again.
At line:1 char:43
+ test-net_port -computerName SZSVR01 -port 23
+                                           ~~
    + CategoryInfo          : InvalidData: (:) [test-net_port], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port
 

PS C:\Users> test-net_port -computerName SZSVR01 -port 22

上一篇
Powershell 入门参数属性(1)
下一篇
Powershell 入门之模块(补充)
系列文
Powershell 入门21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言